/*
 * Created on Oct 18, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.erclab.internal.xpresso.dataAccess;

import com.erclab.internal.xpresso.conf.*;
import com.erclab.internal.xpresso.handlers.*;
import com.erclab.internal.xpresso.exceptions.FormException;
import com.erclab.internal.xpresso.forms.Form;

import java.sql.*;
import java.util.*;
import javax.sql.*;
import org.apache.commons.dbutils.*;
import org.apache.commons.dbutils.handlers.*;


/**
 * @author rodrigen
 *
 */
public class MysqlFormDAO implements FormDAO{

	private final String FORM_QUERY = "SELECT * FROM forms WHERE formName=?";
	private final String FORM_ELEMENTS_QUERY = "SELECT * FROM formelements WHERE idForm=? ORDER BY DisplayOrder";


	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.dataAccess.FormDAO#getFormStatement()
	 */
	public Form createForm(String formName) throws FormException {
		
		Form theForm = null;    
		QueryRunner run = new QueryRunner((DataSource)Settings.getRepository().getRepositoryDataSource(formName));
		ResultSetHandler rsHandler = new BeanHandler(Form.class);
    	
		try {
			theForm = (Form)run.query(FORM_QUERY, formName, rsHandler);
		}catch(SQLException ex){
			throw new FormException("There was an error creating the form '" + formName + "':" + ex);
		}
		return theForm;
	}
	

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.dataAccess.FormDAO#getFormElementsStatement()
	 */
	public void loadFormElements(Form theForm) throws FormException {
		
		// Load the form elements
		String idFormString = "" + theForm.getIdForm();
		ResultSetHandler rsHandler = new FormElementHandler();
		QueryRunner run = new QueryRunner((DataSource)Settings.getRepository().getRepositoryDataSource(theForm.getFormName()));
		try {
			theForm.setFormElements((ArrayList)run.query(FORM_ELEMENTS_QUERY, idFormString, rsHandler));
		}catch(SQLException ex){
			throw new FormException("There was an error loading the form:" + ex);
		}		
	}

}
